package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 统一异常的处理
 * @author: logic-yan
 * @createDate: 2020/4/25
 * @version: 1.0
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.atguigu.gulimail.product.controller")
public class ProductExecptionAdvice {

    /**
     * 处理 JSR303 数据校验错误的异常
     *
     * @return R
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidExecption(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            String message = item.getDefaultMessage();//获取错误信息
            String field = item.getField(); // 获取字段名称
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    /**
     * 统一处理异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handlerException(Throwable throwable){
        log.error("错误信息：{}",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }


}
